// Qt on Metro Stub
// Copyright (c) Andrew Knight
// This software is licensed under the MIT: http://www.opensource.org/licenses/MIT

// Based on code from http://code.msdn.microsoft.com/windowsapps/Direct2D-Basic-Animation-d0a5a4d1, original license:
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

#include "View.h"

using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace D2D1;

#include <QtGui/QApplication>
#include <QtCore/QtPlugin>
#include <QtCore/QPluginLoader>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include "../metro/metroapplication.h"

View::View() :
    m_dpi(96.0f)
{
}

void View::Initialize(
    _In_ CoreWindow^ window,
    _In_ CoreApplicationView^ applicationView
    )
{	
	QApplication::setGraphicsSystem("raster");
	int c = 1; char* v[1] = {""};
	new QApplication(c, v);
	qInstallMsgHandler([](QtMsgType type, const char* msg) {
		OutputDebugStringA(msg);
		OutputDebugStringA("\n");
		if(type == QtFatalMsg)
			abort();
	});
	Q_INIT_RESOURCE(metro);
	Q_IMPORT_PLUGIN(metro);
	MetroApplication* metroApp;
    foreach(QObject* plugin, QPluginLoader::staticInstances()) {
        if (metroApp = qobject_cast<MetroApplication*>(plugin)) {
			qDebug() << "success";
            break;
        }
    }

	if(!metroApp) {
		qFatal("The Qt Metro plugin failed to load");
	}
	
    m_window = window;
    m_applicationView = applicationView;

    m_dpi = static_cast<float>(DisplayProperties::LogicalDpi);

    m_window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);

    DisplayProperties::LogicalDpiChanged += 
        ref new DisplayPropertiesEventHandler(this, &View::OnLogicalDpiChanged);
		
	m_renderer = ref new QtClient(metroApp);
	metroApp->start();
    m_renderer->Initialize(m_window, m_dpi);
}

void View::Run()
{
    m_window->Activate();
	while(true) {
		m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
		QApplication::processEvents();
		m_renderer->Render();
	}
}

void View::OnWindowSizeChanged(
    _In_ CoreWindow^ sender,
    _In_ WindowSizeChangedEventArgs^ args
    )
{
    m_renderer->UpdateForWindowSizeChange();
}

void View::OnLogicalDpiChanged(_In_ Object^ sender)
{
    m_dpi = static_cast<float>(DisplayProperties::LogicalDpi);
    m_renderer->SetDpi(m_dpi);
}